﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Apq.Com;
using System.Data.SqlClient;
using ApqDBManager.Forms;
using ICSharpCode.AvalonEdit;

namespace ApqDBManager.Controls
{
	public partial class ResultTable : UserControl
	{
		public ResultTable()
		{
			InitializeComponent();

			tc.TabPages.Remove(tpInfo);

			_dsBack.Tables.CollectionChanged += new CollectionChangeEventHandler(dsBack_CollectionChanged);
			_dsDisplay.Tables.CollectionChanged += new CollectionChangeEventHandler(dsDisplay_CollectionChanged);
		}

		/// <summary>
		/// 提供UI线程锁
		/// </summary>
		public object LockUI = new object();

		public void SetUILang(Apq.UILang.UILang UILang)
		{
			lock (LockUI)
			{
				#region 工具栏
				tsbExport.Text = UILang["导出(&T)"];
				#endregion

				#region TabControl
				tc.TabPages[0].Text = UILang["结果"];
				tc.TabPages[1].Text = UILang["消息"];
				#endregion
			}
		}

		private void ResultTable_Load(object sender, EventArgs e)
		{
		}

		private long _MaxShowRowCount = 100;
		/// <summary>
		/// 获取或设置显示的最大行数
		/// </summary>
		public long MaxShowRowCount
		{
			get { return _MaxShowRowCount; }
			set { _MaxShowRowCount = value; }
		}

		/// <summary>
		/// 获取显示数据集
		/// </summary>
		public DataSet dsDisplay
		{
			get { return _dsDisplay; }
		}

		/// <summary>
		/// 获取后台数据集
		/// </summary>
		public DataSet dsBack
		{
			get { return _dsBack; }
		}

		#region 数据集事件处理
		// 后台数据集中添加表时,显示数据集添加表
		private void dsBack_CollectionChanged(object sender, CollectionChangeEventArgs e)
		{
			if (e.Action == CollectionChangeAction.Add)
			{//添加表
				DataTable dt = e.Element as DataTable;//无数据
				if (dt != null)
				{
					dt.RowChanged += new DataRowChangeEventHandler(dt_RowChanged);

					DataTable dtDisplay = dt.Clone();

					foreach (DataColumn dc in dtDisplay.Columns)
					{
						if (dc.DataType == typeof(byte[]))
						{
							dc.DataType = typeof(string);
						}
					}

					dsDisplay.Tables.Add(dtDisplay);
				}
			}

			if (e.Action == CollectionChangeAction.Refresh)
			{//清空表
				lock (LockUI)
				{
					Apq.Windows.Delegates.Action_UI<TabPage>(tpRt, tpRt, delegate(TabPage ctrl)
					{
						tpRt.Controls.Clear();
						dsDisplay.Tables.Clear();
					});
				}
			}
		}

		// 后台数据集中进入数据时,复制到显示数据集
		private void dt_RowChanged(object sender, DataRowChangeEventArgs e)
		{
			if (e.Action == DataRowAction.Add)
			{
				DataTable dtDisplay = dsDisplay.Tables[e.Row.Table.TableName];

				bool NeedConvert = false;
				foreach (DataColumn dc in e.Row.Table.Columns)
				{
					if (dc.DataType == typeof(byte[]))
					{
						NeedConvert = true;
					}
				}

				if (_MaxShowRowCount > 0 && dtDisplay.Rows.Count < _MaxShowRowCount)
				{
					if (NeedConvert)
					{
						DataRow dr = dtDisplay.NewRow();
						foreach (DataColumn dc in e.Row.Table.Columns)
						{
							if (dc.DataType == typeof(byte[]))
							{
								dr[dc.ColumnName] = Apq.Data.Common.ConvertToSqlON(e.Row[dc]);
							}
							else
							{
								dr[dc.ColumnName] = e.Row[dc];
							}
						}
						dtDisplay.Rows.Add(dr);
					}
					else
					{
						dtDisplay.ImportRow(e.Row);
					}
				}
			}
		}

		// 显示数据集中添加表时,界面添加表格并绑定到表
		private void dsDisplay_CollectionChanged(object sender, CollectionChangeEventArgs e)
		{
			if (e.Action == CollectionChangeAction.Add)
			{
				DataTable dt = e.Element as DataTable;
				if (dt != null)
				{
					lock (LockUI)
					{
						int idx = _dsDisplay.Tables.IndexOf(dt);
						Apq.Windows.Delegates.Action_UI<TabPage>(tpRt, tpRt, delegate(TabPage ctrl)
						{
							int nX = 3, nY = 9 + 206 * idx;

							//
							// dgv
							//
							DataGridView dgv = new DataGridView();
							dgv.Location = new System.Drawing.Point(nX, nY);
							dgv.Size = new System.Drawing.Size(tpRt.Width - 36, 200);
							dgv.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
							dgv.AutoGenerateColumns = true;
							dgv.ReadOnly = true;
							dgv.AllowUserToAddRows = false;
							dgv.AllowUserToDeleteRows = false;
							dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
							//dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

							tpRt.Controls.Add(dgv);

							// 绑定数据
							dgv.DataSource = _dsDisplay;
							dgv.DataMember = dt.TableName;
							Apq.Windows.Forms.DataGridViewHelper.SetDefaultStyle(dgv);
							Apq.Windows.Forms.DataGridViewHelper.AddBehaivor(dgv);

							// 禁止排序
							foreach (DataGridViewColumn gc in dgv.Columns)
							{
								gc.SortMode = DataGridViewColumnSortMode.NotSortable;
							}

							for (int i = 0; i < dt.Columns.Count; i++)
							{
								// 显示格式:DateTime
								if (dt.Columns[i].DataType.Equals(typeof(DateTime)))
								{
									dgv.Columns[i].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
								}
							}
						});
					}
				}
			}
		}
		#endregion

		//导出
		private void tsbExport_Click(object sender, EventArgs e)
		{
			if (dsBack.Tables.Count > 0)
			{
				DataSet dsOut = dsBack.Copy();
				SqlOut SqlOut = FindForm() as SqlOut;
				// 增加服务器列
				foreach (DataTable dt in dsOut.Tables)
				{
					dt.Columns.Add("__DBIID", typeof(int));
					if (!dt.Columns.Contains("__DBIName"))
					{//分列时多添加一列
						dt.Columns.Add("__DBIName");
					}

					// 设置第一个数据集的服务器名
					// 设置服务器名
					foreach (DataRow dr in dt.Rows)
					{
						dr["__DBIID"] = SqlOut.tc.SelectedTab.Tag;
						dr["__DBIName"] = SqlOut.tc.SelectedTab.Text;
					}
				}

				Export FormE = new Export(dsOut);
				FormE.ShowDialog(this);
			}

			//Apq.Windows.Forms.Wizard w = new Apq.Windows.Forms.Wizard();
			//w.StepIndex = 0;
			//w.btnBack.Click += new EventHandler(btnBack_Click);
			//w.btnNext.Click += new EventHandler(btnNext_Click);
			//w.btnFinish.Click += new EventHandler(btnFinish_Click);
			//w.btnCancel.Click += new EventHandler(btnCancel_Click);

			//ShowExportForm(w, 0, 1);
		}

		/*
		// 添加消息
		public void AddMsg(Apq.Windows.Forms.DockForms.ErrList_XSD.ErrListRow dr)
		{
			lock (LockUI)
			{
				Apq.Windows.Delegates.Action_UI<TabPage>(tpInfo, tpInfo, delegate(TabPage ctrl)
				{
					TextBox txtMsg = new TextBox();
					txtMsg.Multiline = true;
					txtMsg.ReadOnly = true;
					txtMsg.ScrollBars = ScrollBars.Vertical;
					txtMsg.WordWrap = false;
					txtMsg.AcceptsTab = true;
					txtMsg.AcceptsReturn = true;

					txtMsg.BorderStyle = BorderStyle.None;
					txtMsg.BackColor = System.Drawing.SystemColors.Control;
					txtMsg.Font = new System.Drawing.Font("新宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
					txtMsg.Size = new System.Drawing.Size(tc.Width - 30, 20);

					int nY = 9;
					foreach (Control c in tpInfo.Controls)
					{
						nY += c.Size.Height;
						nY += 6;
					}
					txtMsg.Location = new System.Drawing.Point(3, nY);

					if (dr.Severity > 10)
					{
						txtMsg.Size = new System.Drawing.Size(this.Parent.Parent.Width - 40, 140);//7行
						//meMsg.Properties.ScrollBars = System.Windows.Forms.ScrollBars.Both;
						txtMsg.ForeColor = System.Drawing.Color.Red;
					}

					txtMsg.Text += dr.Msg;
					//string.Format("消息 {0}, 级别 {1}, 状态 {2}, 第 {3} 行\r\n", r.Number, r.Class, r.State, r.LineNumber);

					tpInfo.Controls.Add(txtMsg);
				});
			}
		}
		*/
	}
}
